<?php

namespace app\award;

use app\models\NewLevel;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\OrderActive;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\Queue;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;
use app\util\Util;
use yii\helpers\ArrayHelper;

class Award
{
    protected $order;
    protected $user;

    protected $set;

    protected $amount;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $this->amount = $this->order->total_pay - $this->order->total_freight;

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $this->set = SetUserUp::getLastOne();

        $is_bao = ProductArea::checkBao($product_id);
        $is_repeat = ProductArea::checkRepeat($product_id);

        // 排队问题
        // 去掉排队名单
        // $line = $this->line();
        // if ($line) {
        //     return;
        // }

        // 复购
        if ($is_repeat) {
            $this->_diff();
            $this->_team();
        }

        // 新报单
        if ($is_bao) {
            $r = Chain::getReferrer($this->user->id, true);
            if ($r && $r->level >= UserLevel::$keys['vip1']) {

                // 配额处理
                $result = $this->_has($r);
                if (!$result) {

                    /*
                     * 感恩奖是根据推荐奖的平级的
                     * 平级奖是根据团队奖的平级的
                     */

                    $this->_bao($r);
                    // $this->_thanks();
                    $this->_team();
                    // $this->_equal();
                }
            }
        }

    }

    public function line()
    {
        $amount = $this->amount / $this->order->total_quantity;

        $line = 0;
        $query = Order::find()
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']]);
        $count = 0;

        if ($amount == $this->set->vip1) {
            $line = 1;
        }
        if ($amount == $this->set->vip2) {
            $line = 2;
        }
        if ($amount == $this->set->vip3) {
            $line = 3;
        }

        $n = 10;

        // 要加现在这单
        $count = (int)$query->andWhere(['line_done' => 0])->andWhere(['line' => $line])->count();
        $count += 1;

        // 已返的数量也要加上
        $count2 = (int)Order::find()
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->andWhere(['>', 'line_done', 0])
            ->andWhere(['line' => $line])
            ->count();

        // 记录线与第几条
        $this->order->line = $line;
        $this->order->line_ok = $count + $count2;

        $this->order->save();

        // 还要大于 最后 一条返奖的 位置
        $last = Order::find()
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->andWhere(['>', 'line_done', 0])
            ->andWhere(['line' => $line])
            ->orderBy(['id' => SORT_DESC])
            ->one();

        if ($count >= $n && $count % $n == 1) {

            // var_dump($count, $count2);exit;

            if ($last) {
                // var_dump($last->line_done, $count, $count2);exit;
                if ($count <= $last->line_done) {
                    return false;
                }
            }


            $name = '全国免单';
            $type = 101;

            // 返第1位
            $model = Order::find()
                ->orderBy(['id' => SORT_ASC])
                ->where(['line' => $line])
                ->andWhere(['line_done' => 0])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
                ->one();

            if ($model) {
                // 记住是第几位返的
                $model->line_done = $count + $count2;
                $model->save();

                $this->saveCommission($model->user_id, $this->order->total_pay, $type, $name);
                return true;
            }


        }

        return false;
    }

    private function _thanksDiff(User $r)
    {
        $name = '感恩奖';
        $type = 21;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;

        $chain = Chain::getReferrerChain($r->id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
        ], true);

        foreach ($chain as $user) {

            if ($user->level < $r->level) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->set->feel_vip1 / 100 * $this->amount;
                $this->saveCommission($user->id, $diff_vip1, $type, $name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->set->feel_vip2 / 100 * $this->amount;
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $diff_vip2, $type, $name);
                $has_vip2 = true;
            }
            if ((!$has_vip3) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $this->set->feel_vip3 / 100 * $this->amount;
                $diff_vip3 -= $diff_vip1 + $diff_vip2;
                $this->saveCommission($user->id, $diff_vip3, $type, $name);
                $has_vip3 = true;
                break;
            }
        }
    }


    private function _thanks(User $user)
    {
        $name = '感恩奖';
        $type = 21;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;

        $chain = Chain::getReferrerChain($user->id, [
            $user->level
        ], true);
        if ($chain) {
            $chain = $chain[0];

            if ($chain->level == UserLevel::$keys['vip1']) {
                $commission = $this->set->feel_vip1 / 100 * $this->amount;
                $this->saveCommission($chain->id, $commission, $type, $name);
            }
            if ($chain->level == UserLevel::$keys['vip2']) {
                $commission = $this->set->feel_vip1 / 100 * $this->amount;
                $this->saveCommission($chain->id, $commission, $type, $name);
            }
            if ($chain->level == UserLevel::$keys['vip3']) {
                $commission = $this->set->feel_vip1 / 100 * $this->amount;
                $this->saveCommission($chain->id, $commission, $type, $name);
            }
        }

    }


    // 感恩奖
    private function _diff()
    {
        $name = '差价';
        $type = 51;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;

        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
        ], true);

        foreach ($chain as $user) {
            if ((!$has_vip1 && !$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->_diffKey('vip1');
                $this->saveCommission($user->id, $diff_vip1, $type, $name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diffKey('vip2');
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $diff_vip2, $type, $name);
                $has_vip2 = true;
            }
            if ((!$has_vip3) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $this->_diffKey('vip3');
                $diff_vip3 -= $diff_vip1 + $diff_vip2;
                $this->saveCommission($user->id, $diff_vip3, $type, $name);
                $has_vip3 = true;
                break;
            }
        }
    }

    private function _diffKey($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;

        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    // 团队奖
    private function _team()
    {
        $name = '团队奖';
        $type = 31;

        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip3'],
        ], true);

        if ($chain) {
            $user = $chain[0];

            $count = Chain::getChildrenAllQuick($user->id, [
                UserLevel::$keys['vip1'],
                UserLevel::$keys['vip2'],
                UserLevel::$keys['vip3'],
            ]);
            $count = count($count);
            $ration = 0;
            if ($count >= 50) {
                $ration = $this->set->t2;
            } else if ($count >= 10) {
                $ration = $this->set->t1;
            }


            $commission = $ration / 100 * $this->amount;
            $this->saveCommission($user->id, $commission, $type, $name);

            // 平级奖
            // 就算团队数量没有达标, 平级奖依然返
            $this->_equal($user->id);

        }
    }

    // 平级奖
    private function _equal($user_id)
    {
        $name = '平级奖';
        $type = 41;

        // $chain = Chain::getReferrerChain($this->user->id, [
        $chain = Chain::getReferrerChain($user_id, [
            UserLevel::$keys['vip3'],
        ], true);

        if ($chain) {
            $user = $chain[0];
            $commission = $this->set->e / 100 * $this->amount;
            $this->saveCommission($user->id, $commission, $type, $name);
        }
    }

    private function _has($r)
    {
        $award_name = '配额';
        $award_type = 1;

        $amount = $this->amount / $this->order->total_quantity;

        if ($amount == $this->set->vip1) {
            if ($r->has_vip1 >= $this->order->total_quantity) {
                $r->has_vip1 -= $this->order->total_quantity;
                $r->save();

                $this->saveCommission($r->id, $this->amount, $award_type, $award_name);
                return true;

            }
        }
        if ($amount == $this->set->vip2) {
            if ($r->has_vip2 >= $this->order->total_quantity) {
                $r->has_vip2 -= $this->order->total_quantity;
                $r->save();

                $this->saveCommission($r->id, $this->amount, $award_type, $award_name);
                return true;

            }
        }

        return false;
    }

    private function _bao($r)
    {
        $award_name = '开发奖';
        $award_type = 11;

        $amount = $this->amount / $this->order->total_quantity;
        $ratio = 0;

        $children = Chain::getChildren($r->id);
        $children = ArrayHelper::getColumn($children, 'id');

        // 按推三返一, 比例来
        $count = (int)Order::find()
            ->where(['user_id' => $children])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->count();

        $n = $count % 3;
        if ($n == 1) {
            $award_name .= '(第1单)';
            if ($r->level == UserLevel::$keys['vip1']) {
                $ratio = $this->set->vip1_vip1;
            }
            if ($r->level == UserLevel::$keys['vip2']) {
                $ratio = $this->set->vip2_vip1;
            }
            if ($r->level == UserLevel::$keys['vip3']) {
                $ratio = $this->set->vip3_vip1;
            }
        }
        if ($n == 2) {
            $award_name .= '(第2单)';
            if ($r->level == UserLevel::$keys['vip1']) {
                $ratio = $this->set->vip1_vip2;
            }
            if ($r->level == UserLevel::$keys['vip2']) {
                $ratio = $this->set->vip2_vip2;
            }
            if ($r->level == UserLevel::$keys['vip3']) {
                $ratio = $this->set->vip3_vip2;
            }
        }
        if ($n == 0) {
            $award_name .= '(第3单)';
            if ($r->level == UserLevel::$keys['vip1']) {
                $ratio = $this->set->vip1_vip3;
            }
            if ($r->level == UserLevel::$keys['vip2']) {
                $ratio = $this->set->vip2_vip3;
            }
            if ($r->level == UserLevel::$keys['vip3']) {
                $ratio = $this->set->vip3_vip3;
            }
        }

        $commission = $ratio / 100 * $this->amount;
        $this->saveCommission($r->id, $commission, $award_type, $award_name);

        // 高等级差价
        $this->_baoDiff($n, $r, $commission);

        // 感恩奖
        // $this->_thanks($r);
        // 带差价的感恩奖
        $this->_thanksDiff($r);
    }

    // 开发 差价奖
    private function _baoDiff($n, User $r, $vip1_commission)
    {
        $name = '开发差价奖';
        $type = 12;

        $has_vip2 = false;
        $has_vip3 = false;

        $diff_vip2 = 0;
        $diff_vip3 = 0;

        $chain = Chain::getReferrerChain($r->id, [
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
        ], true);

        foreach ($chain as $user) {

            // 这里要去掉平级与低级
            if ($user->level <= $r->level) {
                continue;
            }

            $ratio = 0;

            if ((!$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip2']) {

                if ($n == 1) {
                    $ratio = $this->set->vip2_vip1;
                }
                if ($n == 2) {
                    $ratio = $this->set->vip2_vip2;
                }
                if ($n == 3) {
                    $ratio = $this->set->vip2_vip3;
                }

                $diff_vip2 = $ratio / 100 * $this->amount;
                $diff_vip2 -= $vip1_commission;
                $this->saveCommission($user->id, $diff_vip2, $type, $name);
                $has_vip2 = true;
            }
            if ((!$has_vip3) && $user->level == UserLevel::$keys['vip3']) {

                if ($n == 1) {
                    $ratio = $this->set->vip3_vip1;
                }
                if ($n == 2) {
                    $ratio = $this->set->vip3_vip2;
                }
                if ($n == 3) {
                    $ratio = $this->set->vip3_vip3;
                }

                $diff_vip3 = $ratio / 100 * $this->amount;
                // var_dump($diff_vip3, $vip1_commission, $diff_vip2);exit;
                $diff_vip3 -= $vip1_commission + $diff_vip2;
                $this->saveCommission($user->id, $diff_vip3, $type, $name);
                $has_vip3 = true;
                break;
            }
        }
    }


    // 保存佣金
    protected function saveCommission($user_id, $balance, $type, $name)
    {
        if ($balance >= 0.01) {

            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->user->id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();


            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->balance += $balance;
                $account->save();
            }
        }
    }

    // 2+1 间推
    private function getIndirect($user_id)
    {
        $the_referrer = Chain::getReferrer($user_id, true);
        if (!$the_referrer) {
            return null;
        }

        // 高等级
        if ($the_referrer->level >= UserLevel::$keys['vip3']) {
            // return $the_referrer;
        }

        // 处理两线条
        if ($the_referrer->level >= UserLevel::$keys['vip2']) {

            // 判断是否属于前2个直推
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);
            // var_dump($the_referrer->id, $children);exit;

            // if (count($children) > $this->set->vip2) {
            if (count($children) >= 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($user_id, $children);
                if (!$in) {
                    return $the_referrer;
                } else {
                    return $this->getIndirect($the_referrer->id);
                }
            } else {
                return $this->getIndirect($the_referrer->id);
            }
        }

        return $this->getIndirect($the_referrer->id);
    }
}